import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import fs from 'fs';
import { createHtmlPlugin } from 'vite-plugin-html';

// https://vitejs.dev/config/

const packageInfo = JSON.parse(fs.readFileSync('package.json').toString());

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '') || {};
  return {
    base: env.VITE_UI_BASE_URL,
    plugins: [
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_NAME,
          },
        },
      }),
      react({
      }),
      generateBuildInfoPlugin({ env }),
    ],
    define: {
      'process.env': process.env,
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
    },
    server: {
      proxy: {
        '/portal': {
          target: 'http://127.0.0.1:3000',
          changeOrigin: true,
        },
      },
    },
  };
});

function generateBuildInfoPlugin({ env }) {
  return {
    name: 'vite-plugin-generate-build-info',
    // 在构建完成后生成构建信息文件
    closeBundle() {
      const buildInfo = {
        buildTime: new Date().toISOString(),
        appName: env.VITE_APP_NAME,
        appNameEn: packageInfo?.name,
      };

      const buildInfoPath = path.resolve('dist', 'build.json');
      fs.writeFileSync(buildInfoPath, JSON.stringify(buildInfo, null, 2));

      console.log(`Build info written to ${buildInfoPath}`);
    },
  };
}
